package enumandlambda;

import java.time.LocalDateTime;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author shkstart
 * 读写锁的使用
 * @create 2022-12-11-15:56
 */
public class ReadWriteLockDemo1 {
    public static void main(String[] args) {
        //创建读写锁：
        final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        //创建读锁
        final ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
        //创建写锁
        final ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
        //线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5,
                0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(100));

        //启动新线程执行任务（读操作）
        executor.submit(() -> {
            //读锁的加锁
            readLock.lock();
            try {
                //执行业务逻辑
                System.out.println("执行读锁1：" + LocalDateTime.now());
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //读操作的释放锁
                readLock.unlock();
            }
        });

        //启动读操作执行任务【读操作2】
        executor.submit(() -> { //读操作的加锁
            readLock.lock();
            try {
                //执行业务逻辑
                System.out.println("执行读锁2：" + LocalDateTime.now());
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                readLock.unlock();
            }
        });

        //启动 写操作执行任务 【写操作1】
        executor.submit(()->{
            //写操作的加锁
            writeLock.lock();
            try {
                //执行逻辑业务
                System.out.println("写操作1 ："+LocalDateTime.now());
                TimeUnit.SECONDS.sleep(2);
            }catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                writeLock.unlock();
            }
        });
        //启动 写操作执行任务 【写操作1】
        executor.submit(()->{
            //写操作的加锁
            writeLock.lock();
            try {
                //执行逻辑业务
                System.out.println("写操作2 ："+LocalDateTime.now());
                TimeUnit.SECONDS.sleep(2);
            }catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                writeLock.unlock();
            }
        });
    }
}
